// cart.js
import { Cart } from 'cart-model.js';

var cart = new Cart(); //实例化 购物车

Page({

  data: {
    session_3rd: '',
    cartData: [],     // 购物车数据
    account:0     // 总价格
  },

  onLoad: function (options) {
    
  },
  onShow: function () {
    const that = this
    const session_3rd = this.data.session_3rd
    if (!session_3rd) {
      wx.getStorage({
        key: '3rd_session',
        success: function (res) {
          that.setData({
            session_3rd: res.data
          })
          const session3rd = res.data
          cart.getCartData((data) => {
            let cartData = data.data
            console.log(cartData)
            that.setData({
              cartData
            })
          }, session3rd)
        },
      })
    } else {
      // 获取购物车数据
      const session3rd = this.data.session_3rd
      cart.getCartData((data) => {
        let cartData = data.data
        console.log(cartData)
        that.setData({
          cartData
        })
      }, session3rd)
    }

  },

  // 选中商品列表item
  toggleSelect: function (event) {
    var id = cart.getDataSet(event, 'id'),
      status = cart.getDataSet(event, 'status'),
      index = this._getProductIndexById(id);

    this.data.cartData[index].status = !status;
    this._resetCartData();
  },
  // 重新计算总金额和商品总数
  _resetCartData: function () {
    var newData = this._calcTotalAccountAndCounts(this.data.cartData);
    this.setData({
      account: newData.account,
      selectedCounts: newData.selectedCounts,
      selectedTypeCounts: newData.selectedTypeCounts,
      cartData: this.data.cartData
    });
  },
  // 全选
  toggleSelectAll: function (event) {
    var status = cart.getDataSet(event, 'status') == 'true';
    console.log(status)
    var data = this.data.cartData,
      len = data.length;
    for (let i = 0; i < len; i++) {
      data[i].status = !status;
    }
    this._resetCartData();
  },

  /*根据商品id得到 商品所在下标*/
  _getProductIndexById: function (id) {
    const cartArr = this.data.cartData
    const _index = cartArr.findIndex((item, index) => {
      return item.id == id
    })
    return _index
  },
  // 加加  减减
  changeCounts: function (event) {
    var that = this
    var goods_id = cart.getDataSet(event, 'goodsid'),   // 商品id
      id = cart.getDataSet(event, 'id'),   // 商品种类id
      type = cart.getDataSet(event, 'type'),
      index = this._getProductIndexById(id),
      session3rd = this.data.session_3rd,
      quantity = 1;
    if (type == 'add') {
      const options = {
        session3rd,
        goods_id,
        quantity
      }
      cart.addCounts((res) => {
        console.log(res)
        if (res.status === 0) {
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: res.msg,
            success: function (res) {
              // console.log(res)
            }
          })
        } else {
          that.data.cartData[index].quantity += quantity  // 更新商品数量
          that.setData({
            cartData: that.data.cartData
          })
          that._resetCartData();  // 重新计算总价
        }
      }, options);
    } else {
      quantity = -1;
      const options = {
        session3rd,
        cart_id: id
      }
      // cart.cutCounts(id);
      cart.cutCounts((res) => {
        console.log(res)
        if (res.status === 0) {
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: res.msg,
            success: function (res) {
              // console.log(res)
            }
          })
        } else {
          that.data.cartData[index].quantity += quantity  // 更新商品数量
          that.setData({
            cartData: that.data.cartData
          })
          that._resetCartData();  // 重新计算总价
        }
      }, options);
    }

  },
  // 删除购物车商品
  delete: function (event) {
    const that = this
    const id = cart.getDataSet(event, 'id')
    const index = this._getProductIndexById(id)
    const session3rd = this.data.session_3rd
    const options = {
      session3rd,
      cart_id: id
    }
    wx.showModal({
      title: '提示',
      showCancel: true,
      content: '确定删除此商品？',
      success: function (res) {
        if (res.confirm) {
          // 本地删除
          that.data.cartData.splice(index, 1);  // 删除某一项商品
          // 重新计算价格
          that._resetCartData();
          // 后台删除
          cart.delete((res) => {
            console.log(res)
          }, options)
        } else if (res.cancel) {
          console.log('取消删除')
        }
      }
    })

  },
  // 提交订单
  submitOrder: function (event) {
    wx.navigateTo({
      url: '../order/order?account=' + this.data.account + '&from=cart'
    });
  },
  // 计算商品总数量  总价钱  商品总种类数
  _calcTotalAccountAndCounts: function (data) {
    var len = data.length,
      // 所需要计算的总价格，但是要注意排除掉未选中的商品
      account = 0,
      // 购买商品的总个数
      selectedCounts = 0,
      // 购买商品种类的总数
      selectedTypeCounts = 0;
    let multiple = 100
    let selectProductsArr = []   // 把选中的商品存起来  存到缓存中
    for (let i = 0; i < len; i++) {
      //避免 0.05 + 0.01 = 0.060 000 000 000 000 005 的问题，乘以 100 *100
      if (data[i].status) {
        account += data[i].quantity * multiple * Number(data[i].price) * multiple;
        selectedCounts += data[i].quantity;
        selectedTypeCounts++;
        selectProductsArr.push(data[i])
      }
    }
    // 选中商品存入缓存中
    wx.setStorage({
      key: 'selectProductsArr',
      data: selectProductsArr
    })
    return {
      selectedCounts,
      selectedTypeCounts,
      account: account / (multiple * multiple)
    }
  },

})